package com.example.cinema.controller;

import com.example.cinema.dto.UserDTO;
import com.example.cinema.model.User;
import com.example.cinema.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody Map<String, String> request) {
        try {
            String username = request.get("username");
            String password = request.get("password");
            String email = request.get("email");

            User user = userService.registerUser(username, password, email);
            String successMessage = "注册成功！用户ID: " + user.getId();
            System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " - " + successMessage);
            return new ResponseEntity<>(successMessage, HttpStatus.CREATED);
        } catch (RuntimeException e) {
            String errorMessage = "注册失败: " + e.getMessage();
            System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " - " + errorMessage);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }

    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<?> loginUser(@RequestBody Map<String, String> request) {
        try {
            String username = request.get("username");
            String password = request.get("password");

            User user = userService.loginUser(username, password);
            String successMessage = "登录成功！欢迎回来，" + user.getUsername() + "！";
            System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " - " + successMessage);
            return new ResponseEntity<>(successMessage, HttpStatus.OK);
        } catch (RuntimeException e) {
            String errorMessage = "登录失败: " + e.getMessage();
            System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " - " + errorMessage);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }

    // 获取所有用户列表（不包含密码）
    @GetMapping("/all")
    public ResponseEntity<List<UserDTO>> getAllUsers() {
        List<UserDTO> users = userService.listAllUsers();
        return new ResponseEntity<>(users, HttpStatus.OK);
    }

    // 获取用户角色
    @PostMapping("/role")
    public ResponseEntity<?> getUserRole(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        if (username == null || username.isEmpty()) {
            return ResponseEntity.badRequest().body("Username cannot be empty");
        }
        String role = userService.getUserRole(username);
        if (role == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("User not found or no role assigned");
        }
        return ResponseEntity.ok(Collections.singletonMap("role", role));
    }

    // 设置用户角色
    @PostMapping("/role/set")
    public ResponseEntity<?> setUserRole(@RequestBody Map<String, String> request) {
        try {
            String username = request.get("username");
            String roleName = request.get("roleName");

            if (username == null || username.isEmpty() || roleName == null || roleName.isEmpty()) {
                return new ResponseEntity<>("用户名和角色名不能为空", HttpStatus.BAD_REQUEST);
            }

            userService.setUserRole(username, roleName);
            return new ResponseEntity<>("角色设置成功", HttpStatus.OK);
        } catch (RuntimeException e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }
}